/*
 * Copyright (c) 2013-2018 上海汇数数据. All rights reserved.
 * @(#) DName.java 2018-08-06 17:26
 */

package cn.jh.common.core.crypto;

import cn.jh.common.core.base.Joiners;
import cn.jh.common.core.base.Splitters;
import org.inferred.freebuilder.FreeBuilder;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import static com.google.common.base.Preconditions.checkArgument;


/**
 * cn=test,ou=test,o=test,l=Shanghai,st=Shanghai,c=CN
 *
 * @author Fuchun
 * @since 1.0
 */
@FreeBuilder
public interface DName {

    static DName fromString(String dName) {
        Map<String, String> pairMap = Splitters.commaEqualMap().split(dName);
        Map<String, String> parts = new HashMap<>(pairMap.size());
        for (Map.Entry<String, String> entry : pairMap.entrySet()) {
            String key = entry.getKey(), value = entry.getValue();
            parts.put(key.toUpperCase(), value);
        }
        checkArgument(parts.size() == 6, "The dname (%s) is in valid.", dName);
        return new Builder()
                .setCn(parts.get("CN"))
                .setOu(parts.get("OU"))
                .setO(parts.get("O"))
                .setL(parts.get("L"))
                .setS(parts.get("S"))
                .setC(parts.get("C")).build();
    }

    static String toString(DName dName) {
        LinkedHashMap<String, String> parts = new LinkedHashMap<>(6);
        parts.put("CN", dName.getCn());
        parts.put("OU", dName.getOu());
        parts.put("O", dName.getO());
        parts.put("L", dName.getL());
        parts.put("S", dName.getS());
        parts.put("C", dName.getC());
        return Joiners.commaEqualMap().join(parts);
    }

    /** 名字与姓氏（或者是域名），common Name */
    String getCn();

    /** 组织单位名称 organization Unit */
    String getOu();

    /** 组织名称 organization Name */
    String getO();

    /** 城市或区域名称。 locality Name */
    String getL();

    /** 所在省、市、自治区名称。 state Name */
    String getS();

    /** 双字母国家、地区代码。country */
    String getC();

    class Builder extends DName_Builder {

    }
}
